package com.easytouch.core.task;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by gulin on 2017/8/18.
 */

public class TaskThreadPool {

    private static ExecutorService executorService = Executors.newCachedThreadPool();
    private static Set<String> identifierSet = new HashSet<String>();
    private static long mLastAddIdentifierTime = 0;

    public static synchronized boolean addIdentifier(final String pIdentifier) {
        boolean result;
        if (pIdentifier == null) {
            result = false;
        } else {
            if (identifierSet.contains(pIdentifier)) {
                result = false;
            } else {
                result = true;
            }
        }
        long currentTime = System.currentTimeMillis();
        if (currentTime - mLastAddIdentifierTime > 1000 * 60 * 10) //10分钟之后删除掉所有记录
        {
            identifierSet.clear();
        }
        if (result) {
            identifierSet.add(pIdentifier);
            mLastAddIdentifierTime = currentTime;
        }
        return result;
//        for (int i = 0;i < identifierList.size();i++)
//        {
//            String identifier = identifierList.get(i);
//            if(pIdentifier.equals(identifier))
//            {
//                return false;
//            }
//        }
    }

    public static synchronized void deleteIdentifier(String content) {
        identifierSet.remove(content);
    }


    public static synchronized void removeIdentifier(final String pIdentifier)
    {
        //这个方法现在什么都不做
//        for (int i = 0;i < identifierList.size();i++)
//        {
//            String identifier = identifierList.get(i);
//            if(pIdentifier.equals(identifier))
//            {
//                identifierList.remove(i);
//                break;
//            }
//        }
    }


    public static boolean addTaskAndRun(final Task pTask)
    {
        if(pTask == null)
            return false;
        if(!addIdentifier(pTask.getIdentifier()))
            return false;
        executorService.execute(pTask);
        return true;
    }


}
